<template>
  <el-dialog
    title="自定义字段"
    v-model="dialogVisible"
    v-if="load"
    :close-on-click-modal="false"
    width="900"
    @close="close"
    :z-index="2000"
  >
    <el-row class="py-2" :gutter="21">
      <el-col class="border-r border-[var(--base-border-color)]" :span="15">
        <div class="py-1 border-b border-[var(--base-border-color)]">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
        </div>
        <div class="checkbox-group mt-2">
          <div class="checkbox" v-for="item in headerList" :key="item.field">
            <el-checkbox
              v-model="item.show"
              :true-label="1"
              :false-label="0"
              @change="handleCheckedChange"
              >{{ item.field == "checkbox" ? "勾选项" : item.title }}</el-checkbox
            >
          </div>
        </div>
      </el-col>
      <el-col :span="9">
        <div class="border border-[var(--base-border-color)]">
          <div
            class="flex py-2 px-2 bg-[var(--base-table-header-bg-color)] text-[#333333]"
          >
            <div>展示顺序（拖动调整）</div>
            <el-button type="primary" link @click="restoreDefault">恢复默认</el-button>
          </div>
          <div class="px-2">
            <VueDraggableNext v-model="headerList">
              <div
                class="flex items-center my-1 py-1 cursor-pointer"
                v-for="item in headerList"
                :key="item.field"
              >
                <svg-icon class="mr-1 text-[#999999]" icon-class="tuodong"></svg-icon
                ><span class="">{{
                  item.field == "checkbox" ? "勾选项" : item.title
                }}</span>
              </div>
            </VueDraggableNext>
          </div>
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <el-button class="ml-5" @click="close">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>
<script name="pictureDialog" setup>
import { computed, reactive, toRefs } from "vue";
import { VueDraggableNext } from "vue-draggable-next";
import { setCustomFields } from "../api/index.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  columns: {
    type: Array,
    default: () => {
      return [];
    },
  },
  apiName: {
    type: String,
    default: "",
  },
});

const { columns, apiName } = toRefs(props);

const emits = defineEmits("filterTable");

const data = reactive({
  dialogVisible: false,
  checkAll: false,
  isIndeterminate: false,
  headerList: [],
  load: false,
});

const { dialogVisible, checkAll, isIndeterminate, headerList, load } = toRefs(data);

const handleCheckAllChange = (val) => {
  headerList.value.forEach((i) => {
    i.show = val ? 1 : 0;
  });
  isIndeterminate.value = false;
};

const handleCheckedChange = () => {
  const isChecked = headerList.value.some((i) => i.show);
  const isAllChecked = headerList.value.every((i) => i.show);
  isIndeterminate.value = isChecked;
  checkAll.value = isAllChecked;
  if (isAllChecked) isIndeterminate.value = false;
};

const restoreDefault = () => {
  const custom_list = [];
  columns.value
    .filter((i) => i.field != "checkbox" && i.field != "operation")
    .forEach((i) => {
      const matchingField = headerList.value.find((j) => i.field === j.field);
      const customObject = {
        title: i.title,
        field: i.field,
        show: matchingField?.show || 0,
      };
      const existingObjectIndex = custom_list.findIndex((obj) => obj.field === i.field);
      if (existingObjectIndex !== -1) {
        custom_list[existingObjectIndex] = customObject;
      } else {
        custom_list.push(customObject);
      }
    });
  headerList.value = custom_list;
};

const save = async () => {
  try {
    const res = await setCustomFields({
      apiName: apiName.value,
      fields: headerList.value,
    });
    ElMessage.success("操作成功");
    emits("filterTable");
    close();
  } catch (e) {
    throw Error(e);
  }
};

const open = async (customFields) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (customFields && customFields.length) {
    const custom_list = [];
    customFields.forEach((customField) => {
      const column = columns.value.find((column) => column.field === customField.field);
      if (column?.field != "checkbox" && column?.field != "operation") {
        const customObject = {
          title: column ? column.title : "",
          field: customField.field,
          show: customField.show || 0,
        };
        custom_list.push(customObject);
      }
    });
    columns.value.forEach((column) => {
      const isColumnInCustomList = custom_list.some(
        (customObject) => customObject.field === column.field
      );
      if (
        !isColumnInCustomList &&
        column?.field != "checkbox" &&
        column?.field != "operation"
      ) {
        const customObject = {
          title: column.title || "",
          field: column.field,
          show: 0,
        };
        custom_list.push(customObject);
      }
    });
    headerList.value = custom_list;
    handleCheckedChange();
  } else {
    const custom_list = [];
    columns.value.forEach((i) => {
      if (i.field) {
        custom_list.push({
          title: i.title,
          field: i.field,
          show: 0,
        });
      }
    });
    headerList.value = custom_list;
    handleCheckedChange();
  }
  dialogVisible.value = true;
};

const close = () => {
  dialogVisible.value = false;
};

defineExpose({ open, close });
</script>
<style scoped>
:deep(.v-page .el-dialog__body, body .el-dialog__body) {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.checkbox {
  width: 33%;
  margin-right: 0;
}
</style>
